#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author          : ricsy
@File            : theme_config_manager.py
@Create Time     : 2025/6/10 06:14
@Last Modified   :
@Description     :
"""
import os
import re
from typing import Dict, List, Union

from src.settings import logger
from utils.config_processor import ConfigProcessor
from utils.time_utils import TimeUtils


config = ConfigProcessor()
static_dir = config.get_static_dir()
scss_output_path = static_dir / "assets/scss/_config" / "_index.scss"


class ThemeConfigManager:
    """主题配置管理器，负责从 config.toml 加载配置并生成 SCSS 变量"""

    def __init__(self):
        """
        初始化
        """
        self.scss_output_path = scss_output_path
        self._style_config = config.get_section("style")
        self.env_prefix_patterns = config.get_section("security").get(  # 默认 INK_ 前缀
            "getenv", ["^INK_"]
        )

    def _is_allowed_env_var(self, key: str) -> bool:
        """检查环境变量是否匹配允许的前缀规则"""
        return any(re.match(pattern, key) for pattern in self.env_prefix_patterns)

    @staticmethod
    def _parse_env_value(value: str) -> Union[str, List[str]]:
        """解析环境变量值（自动处理列表类型）"""
        if "," in value:
            return [v.strip() for v in value.split(",")]
        return value

    def _load_environment_vars(self) -> Dict[str, Union[str, List[str]]]:
        """加载符合前缀规则的环境变量"""
        env_config = {}

        for key, value in os.environ.items():
            if self._is_allowed_env_var(key):
                # 移除前缀并转为小写
                clean_key = re.sub(r"^[^_]*_", "", key).lower()  # 移除前缀部分
                env_config[clean_key] = self._parse_env_value(value)

        return env_config

    @staticmethod
    def _to_scss_value(value: Union[str, List]) -> str:
        """将Python值转换为SCSS合法值"""
        if isinstance(value, list):
            return f"({', '.join(value)})"
        return f'"{value}"' if " " in str(value) else str(value)

    def generate_scss_variables(self) -> str:
        """生成SCSS变量内容"""
        scss_lines = [
            "// 自动生成的样式变量 (来自config.toml)",
            f"// 允许的环境变量前缀: {self.env_prefix_patterns}",
            f"// 生成时间: {TimeUtils.get_full_datetime()}\n",
        ]

        env_config = self._load_environment_vars()
        for key, value in env_config.items():
            scss_name = f"env-{key.replace('_', '-')}"
            scss_lines.append(f"${scss_name}: {self._to_scss_value(value)};")

        for key, value in self._style_config.items():
            # 转换配置键名：some_key -> some-key
            scss_name = key.replace("_", "-")

            # 处理特殊值类型
            if isinstance(value, bool):
                value = "true" if value else "false"
            elif isinstance(value, (int, float)):
                value = (
                    f"{value}px"
                    if key.endswith(("width", "height", "size"))
                    else str(value)
                )

            scss_lines.append(f"${scss_name}: {value};")

        return "\n".join(scss_lines)

    def write_scss_file(self) -> bool:
        """将SCSS变量写入文件"""
        if not self.scss_output_path:
            return False

        try:
            scss_content = self.generate_scss_variables()
            self.scss_output_path.parent.mkdir(parents=True, exist_ok=True)
            self.scss_output_path.write_text(scss_content, encoding="utf-8")
            return True
        except IOError as e:
            logger.error(f"SCSS变量写入失败 - {str(e)}")
            return False

    # noinspection PyUnusedLocal
    def setup_sphinx_extension(self):
        """注册为Sphinx扩展"""
        # 生成SCSS文件
        if self.scss_output_path:
            self.write_scss_file()
        else:
            logger.warning("SCSS 输出文件不存在")
